import { nextTick, watch, onUnmounted, onActivated } from "vue";
import { storeToRefs } from "pinia";
import { useThemeConfig } from "/@/stores/themeConfig";
import { useTagsViewRoutes } from "/@/stores/tagsViewRoutes";

const { themeConfig } = storeToRefs(useThemeConfig());
const { isTagsViewCurrenFull } = storeToRefs(useTagsViewRoutes());

export function useEcharts(chartOption: any, resize: () => void, updateChart: () => void) {
	// 监听 pinia 中 tagsview 是否开启全屏
	const isFullUnWatch = watch(
		() => isTagsViewCurrenFull.value,
		() => resize()
	);

	// 监听 pinia 中是否开启菜单水平折叠
	const isCollUnWatch = watch(
		() => themeConfig.value.isCollapse,
		() => setTimeout(() => resize(), 500)
	);

	// 监听 pinia 中是否开启深色主题
	const isDarkUnWatch = watch(
		() => themeConfig.value.isIsDark,
		isIsDark => {
			nextTick(() => {
				chartOption.theme = isIsDark ? "dark" : "";
				chartOption.bgColor = isIsDark ? "transparent" : "";
				chartOption.color = isIsDark ? "#dadada" : "#303133";
				setTimeout(() => updateChart(), 500);
			});
		},
		{ immediate: true }
	);

	// 生命周期
	onActivated(() => resize());
	onUnmounted(() => {
		isFullUnWatch();
		isCollUnWatch();
		isDarkUnWatch();
		window.removeEventListener("resize", resize);
	});
}
